package com.wmd.core.operation;

import com.deepoove.poi.XWPFTemplate;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfGraphicsUnit;
import com.spire.pdf.graphics.PdfUnitConvertor;
import com.spire.pdf.widget.PdfPageCollection;
import com.wmd.core.exceptions.MyException;
import com.wmd.core.util.CharacterUtils;
import com.wmd.core.util.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.*;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class FileOperation {
    private static Log logger = LogFactory.getLog(FileOperation.class);

    public String getUploadPath() {
        String path1 = System.getProperty("user.dir");
        // System.out.println("getUploadPath:"+path1);
        return path1;
    }


    public static String uploadFile(MultipartFile file, HttpServletRequest request, String path) throws IOException {
        logger.info("start upload file:" + file.getName());
        // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String path2 = "/" + file.getName() + "/";
        String fileName = new Date().getTime() + "_" + file.getOriginalFilename();
        fileName = fileName.replace("&", "").replace(",", "");// 防止url参数混乱
        File targetFile = new File(new File(path + path2).getAbsoluteFile(), fileName);
        logger.info("target file path:" + targetFile.getAbsolutePath());
        if (!targetFile.exists()) {
            targetFile.getParentFile().mkdirs();
        }

        file.transferTo(targetFile);

        return path2 + fileName;
    }
    public static void download(String path, HttpServletResponse response, boolean isOnLine) {
        File file = new File(path);
        download(file, response, isOnLine,null);
    }
    public static void download(String path, HttpServletResponse response, boolean isOnLine,String downloadFileName) {
        File file = new File(path);
        download(file, response, isOnLine,downloadFileName);
    }
    public static void download(File file, HttpServletResponse response, boolean isOnLine){
        download(file,response,isOnLine,null);
    }
    public static void download(File file, HttpServletResponse response, boolean isOnLine,String downloadFileName) {
        try {
            String filename =StringUtil.isEmpty(downloadFileName)? file.getName():downloadFileName;
            InputStream fis = new BufferedInputStream(new FileInputStream(file));


            //response.reset();
            response.setCharacterEncoding("UTF-8");
            if (isOnLine) { // 在线打开方式
                URL u = new URL("file:///" + file.getAbsolutePath());
                response.setContentType(u.openConnection().getContentType());
                response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(filename, "UTF-8"));
                // 文件名应该编码成UTF-8
            } else { // 纯下载方式
//				response.setContentType("application/x-msdownload");
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            }
            response.addHeader("Content-Length", file.length() + "");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());


            byte[] buffer = new byte[1000];
            while (fis.read(buffer) > 0) {
                toClient.write(buffer);
            }
            ;
            fis.close();
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    public static void downloadDocx(XWPFTemplate xwpfTemplate,HttpServletResponse response, boolean isOnLine,String downloadFileName){
        String filename =StringUtil.isEmpty(downloadFileName)? "download.docx":downloadFileName;
        try {
            //response.reset();
            response.setCharacterEncoding("UTF-8");
            if (isOnLine) { // 在线打开方式
                response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(filename, "UTF-8"));
                // 文件名应该编码成UTF-8
            } else { // 纯下载方式
//				response.setContentType("application/x-msdownload");
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            }
            OutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            xwpfTemplate.write(bos);
            xwpfTemplate.close();
            bos.flush();
            bos.close();
            out.flush();
            out.close();
        }catch (IOException ex) {
            ex.printStackTrace();
        }finally {

        }
    }

    public static class UrlFileInfo {
        public String name;
        public String ext;
        public long size;
        public String urlString;
    }

    public static UrlFileInfo getUrlFileInfo(String urlString) {
        URL url = null;
        UrlFileInfo urlFileInfo = new UrlFileInfo();
        try {
            urlString= URLDecoder.decode(urlString,"UTF-8");
            urlFileInfo.name = urlString.substring(urlString.lastIndexOf("/") + 1);
            urlFileInfo.ext = urlString.substring(urlString.lastIndexOf("."));
//            if (urlString.contains("\\")) {
//                urlString = urlString.replace("\\", "/");
//            }
//            String[] urlspits = urlString.split("/");
//            StringBuffer stringBuffer = new StringBuffer();
//            for (int i = 0; i < urlspits.length; i++) {
//                if (i > 0) {
//                    stringBuffer.append("/");
//                }
//                if (i > 2) {
//                    String encodeString = URLEncoder.encode(urlspits[i], "UTF-8");
//                    encodeString = encodeString.replace("+", "%20");
//                    stringBuffer.append(encodeString);
//                } else {
//                    stringBuffer.append(urlspits[i]);
//                }
////                stringBuffer.append(CharacterUtils.isContainChinese(urlspits[i]) ? URLEncoder.encode(urlspits[i], "UTF-8") : urlspits[i]);
//            }
            urlFileInfo.urlString=FormatUrlString(urlString);
            url = new URL(urlFileInfo.urlString);
            HttpURLConnection httpConnectionAlerady = (HttpURLConnection) url.openConnection();
            httpConnectionAlerady.setRequestMethod("HEAD");
            long FileSize = httpConnectionAlerady.getContentLengthLong();
//			HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            String contentType = httpConnectionAlerady.getContentType();
            int code = httpConnectionAlerady.getResponseCode();
            if (code != 200 || FileSize <= 0) {
                throw new MyException(500, "文件路径错误或网络不可访问:"+url.toString(), null);
            } else {
                String ContentDisposition=httpConnectionAlerady.getHeaderField("Content-Disposition");
                if(!StringUtil.isEmpty(ContentDisposition)){
                    String[] cds=ContentDisposition.split(";");
                    for(String cd : cds){
                        if(cd.contains("filename")){
                            String[] fns=cd.split("=");
                            if(fns.length>1){
                                urlFileInfo.name = fns[1];
                                urlFileInfo.ext = fns[1].substring(fns[1].lastIndexOf("."));
                            }
                            break;
                        }
                    }
                }
                urlFileInfo.size = FileSize;
                return urlFileInfo;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return urlFileInfo;
    }
    public static String FormatUrlString(String urlString) throws UnsupportedEncodingException {
            if (urlString.contains("\\")) {
                urlString = urlString.replace("\\", "/");
            }
            String tail="";
            if(urlString.contains("?")){
                int firstparaindex=urlString.indexOf("?");
                String pre=urlString.substring(0,firstparaindex);
                String suf=urlString.substring(firstparaindex,urlString.length());
                urlString=pre;
                tail=suf;
            }
            String[] urlspits = urlString.split("/");
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < urlspits.length; i++) {
                if (i > 0) {
                    stringBuffer.append("/");
                }
//                stringBuffer.append(CharacterUtils.isContainChinese(urlspits[i]) ? URLEncoder.encode(urlspits[i], "UTF-8") : urlspits[i]);
                if (i > 2) {
                    String encodeString = URLEncoder.encode(urlspits[i], "UTF-8");
                    encodeString = encodeString.replace("+", "%20");
                    stringBuffer.append(encodeString);
                } else {
                    stringBuffer.append(urlspits[i]);
                }
            }
            if(tail.length()>0){
                stringBuffer.append(tail);
            }
            return stringBuffer.toString();
    }


    public static boolean downloadUrlToResponse(String urlString, String fileName, HttpServletResponse response, boolean isOnLine) {

        URL url;
        try {
//			if(urlString.contains("?")){
//				urlString+="&t="+System.currentTimeMillis();
//			}else{
//				urlString+="?t="+System.currentTimeMillis();
//			}
//            if (urlString.contains("\\")) {
//                urlString = urlString.replace("\\", "/");
//            }
//            String[] urlspits = urlString.split("/");
//            StringBuffer stringBuffer = new StringBuffer();
//            for (int i = 0; i < urlspits.length; i++) {
//                if (i > 0) {
//                    stringBuffer.append("/");
//                }
////                stringBuffer.append(CharacterUtils.isContainChinese(urlspits[i]) ? URLEncoder.encode(urlspits[i], "UTF-8") : urlspits[i]);
//                if (i > 2) {
//                    String encodeString = URLEncoder.encode(urlspits[i], "UTF-8");
//                    encodeString = encodeString.replace("+", "%20");
//                    stringBuffer.append(encodeString);
//                } else {
//                    stringBuffer.append(urlspits[i]);
//                }
//            }
            url = new URL(FormatUrlString(urlString));
            HttpURLConnection httpConnectionAlerady = (HttpURLConnection) url.openConnection();

//			HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
//			httpConnection.setRequestMethod("HEAD");
            long removeFileSize = httpConnectionAlerady.getContentLengthLong();
            String contentType = httpConnectionAlerady.getContentType();
            int code = httpConnectionAlerady.getResponseCode();
            if (code != 200 || removeFileSize <= 0) {
                throw new MyException(500, "文件路径错误或网络不可访问:"+url.toString(), null);
            }
//			httpConnection.disconnect();
            //response.reset();
            response.setCharacterEncoding("UTF-8");
            if (isOnLine) { // 在线打开方式
                response.setContentType(contentType);
                response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(fileName, "UTF-8"));
                // 文件名应该编码成UTF-8
            } else { // 纯下载方式
//				response.setContentType("application/x-msdownload");
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            }
            response.addHeader("Content-Length", removeFileSize + "");


            ReadableByteChannel src = Channels.newChannel(httpConnectionAlerady.getInputStream());
            WritableByteChannel dest = Channels.newChannel(response.getOutputStream());
            ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
            while (src.read(buffer) != -1) {
                // 切换为读状态
                //兼容java8
                ((Buffer)buffer).flip();
                // 保证缓冲区的数据全部写入
                while (buffer.hasRemaining()) {
                    dest.write(buffer);
                }
                // 清除缓冲区
                ((Buffer)buffer).clear();
            }
            httpConnectionAlerady.disconnect();
            return true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw MyException.create(500,e.getMessage(),urlString);
//            return false;
        }
    }

    public static boolean downloadUrl(String path, String urlString) {

        URL url;
        try {
            if (urlString.contains("\\")) {
                urlString = urlString.replace("\\", "/");
            }
            String[] urlspits = urlString.split("/");
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < urlspits.length; i++) {
                if (i > 0) {
                    stringBuffer.append("/");
                }
//                stringBuffer.append(CharacterUtils.isContainChinese(urlspits[i]) ? URLEncoder.encode(urlspits[i], "UTF-8") : urlspits[i]);
                if (i > 2) {
                    String encodeString = URLEncoder.encode(urlspits[i], "UTF-8");
                    encodeString = encodeString.replace("+", "%20");
                    stringBuffer.append(encodeString);
                } else {
                    stringBuffer.append(urlspits[i]);
                }
            }
            url = new URL(stringBuffer.toString());
            HttpURLConnection httpConnectionAlerady = (HttpURLConnection) url.openConnection();

//			HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
//			httpConnection.setRequestMethod("HEAD");
            long removeFileSize = httpConnectionAlerady.getContentLengthLong();
            int code = httpConnectionAlerady.getResponseCode();
            if (code != 200 || removeFileSize <= 0) {
                throw new MyException(500, "文件路径错误或网络不可访问:+"+url.toString(), null);
            }


            File outputFile = new File(path);
            if (!outputFile.exists()) {
                outputFile.getParentFile().mkdirs();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(outputFile, false);

            ReadableByteChannel readableByteChannel = Channels.newChannel(httpConnectionAlerady.getInputStream());
            FileChannel fileChannel = fileOutputStream.getChannel();
            fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
            httpConnectionAlerady.disconnect();
            readableByteChannel.close();
            fileChannel.close();
            fileOutputStream.close();
            return true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw MyException.create(500,e.getMessage(),urlString);
//            return false;
        }
    }

    public static void downloadXls(String fileName, Workbook workbook, HttpServletResponse response, HttpServletRequest request) {
        try {
            //response.reset();
//			String formFileName=fileName;
//			String userAgent = request.getHeader("User-Agent");
//			// 针对IE或者以IE为内核的浏览器：
//			if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
//				formFileName = java.net.URLEncoder.encode(formFileName, "UTF-8");
//			} else {
//				// 非IE浏览器的处理：
//				formFileName = new String(formFileName.getBytes("UTF-8"), "ISO-8859-1");
//			}
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // response.addHeader("Content-Length", file.length() + "");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
//			response.setContentType("application/vnd.ms-excel;charset=UTF-8");

            workbook.write(toClient);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static boolean deleteFile(String path) {
        File file = new File(path);
        return deleteFile(file);
    }

    public static boolean deleteFile(File file) {
        if ((file.exists()) && (file.isFile())) {
            if (file.delete()) {
                return true;
            }
            return false;
        }
        return false;
    }

    public static void delFolder(String folderPath) {
        delAllFile(folderPath);
    }

    public static boolean deleteEmptyFolder(String folderPath) {
        File f = new File(folderPath);
        return deleteEmptyFolder(f);
    }

    public static boolean deleteEmptyFolder(File f) {
        if (f.isDirectory()) {
            File[] files = f.listFiles();
            if (files == null || files.length <= 0) {
                f.delete();
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public static boolean delAllFile(String path) {
        File file = new File(path);
        return delAllFile(file);
    }

    public static boolean delAllFile(File dirFile) {
        // 如果dir对应的文件不存在，则退出
        if (!dirFile.exists()) {
            return false;
        }

        if (dirFile.isFile()) {
            return dirFile.delete();
        } else {
            for (File file : dirFile.listFiles()) {
                delAllFile(file);
            }
            return dirFile.delete();
        }
    }

    public static void copyNio(String source, String dest) {
        copyNio(new File(source), new File(dest));
    }

    public static void copyNio(File source, File dest) {
        FileChannel input = null;
        FileChannel output = null;
        try {
            input = new FileInputStream(source).getChannel();
            output = new FileOutputStream(dest).getChannel();
            output.transferFrom(input, 0, input.size());
            output.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static List<int[]> getUrlPdfInfo(String urlString) throws IOException {
        URL url = null;
        url = new URL(FormatUrlString(urlString));
        HttpURLConnection httpConnectionAlerady = (HttpURLConnection) url.openConnection();
        PdfDocument document = new PdfDocument();
        document.loadFromStream(httpConnectionAlerady.getInputStream());
        return getPdfInfo(document);
    }
    public static List<int[]> getFilePdfInfo(String filepath){
        PdfDocument document = new PdfDocument();
        document.loadFromFile(filepath);
        return getPdfInfo(document);
    }
    public static List<int[]> getISPdfInfo(InputStream is,String savePath,boolean save){
        PdfDocument document = new PdfDocument();
        if(save){
            try {
                saveInputStream(is,savePath);
                document.loadFromFile(savePath);
            } catch (IOException e) {
                logger.error(e.getMessage());
                return new ArrayList<>();
            }
        }else{
            document.loadFromStream(is);
        }
        return getPdfInfo(document);
    }
    public static void saveInputStream(InputStream is,String savePath) throws IOException {
        FileOutputStream fileOutputStream = null;
        fileOutputStream = new FileOutputStream(savePath, false);
        ReadableByteChannel readableByteChannel = Channels.newChannel(is);
        FileChannel fileChannel = fileOutputStream.getChannel();
        fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
        readableByteChannel.close();
        fileChannel.close();
        fileOutputStream.close();
    }
    public static List<int[]> getPdfInfo(PdfDocument document){
        PdfPageCollection pages = document.getPages();
        int pn= pages.getCount();
        List<int[]> pageInfo=new ArrayList<>();
        for(int i=0;i<pn;i++){
            PdfPageBase page = pages.get(i);
            //获取第一页页面宽度、高度
            float pointWidth = (float) page.getSize().getWidth();
            float pointHeight = (float) page.getSize().getHeight();

            //将度量单位转换为厘米
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            float millimeterWidth = unitCvtr.convertUnits(pointWidth, PdfGraphicsUnit.Point, PdfGraphicsUnit.Millimeter);
            float millimeterHeight = unitCvtr.convertUnits(pointHeight, PdfGraphicsUnit.Point, PdfGraphicsUnit.Millimeter);

            int mmWidth=Math.round(millimeterWidth);
            int mmHeight=Math.round(millimeterHeight);
            pageInfo.add(new int[]{mmWidth,mmHeight});
            //输出页面大小
//            System.out.println("该PDF的页面大小为(宽: " + pointWidth + "pt, 高: " + pointHeight + "pt).");
//            System.out.println("该PDF的页面大小为(宽: " + millimeterWidth + "mm, 高: " + millimeterHeight + "mm.)");
//            System.out.println("该PDF的页面大小为(宽: " + mmWidth + "mm, 高: " + mmHeight + "mm.)");
        }
        return pageInfo;
    }

    public static String getFileExt(String filename){
       return filename.substring(filename.lastIndexOf("."));
    }
    public static String getFileName(String filename){
       return filename.substring(0,filename.lastIndexOf("."));
    }
}

/*
 * Location: C:\Users\Administrator\Desktop\YKTP\WEB-INF\classes\
 *
 * Qualified Name: com.YKTP.util.FileUpload
 *
 * JD-Core Version: 0.7.0.1
 *
 */